/**
 * Created by camiez on 2017/4/3.
 */
'use strict';
const bookApi = {};
const db = require('../../mysql.js');
const fs = require('fs');
/**
 * 获取所有小说api
 * @param req
 * @param res
 * @param next
 */
bookApi.getAllBooks = function(req,res,next){
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select * from book ',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select * from book limit 13 offset '+offset,[],function(result){
            res.send(result);
        });
    }
}
bookApi.getNeedAddBook = function (req,res,next) {
    db.query('select * from book where chapter = "no"',[],function (result) {
        res.send(result);
    })
}
/**
 * 根据获取到的需要删除的书本的id删除数据库中的书
 * @param req
 * @param res
 * @param next
 */
bookApi.deleteBook = function(req,res,next){
    var deleteBookId = req.params.deleteBookId;
    db.query('delete from book where bookId=?',[deleteBookId],function(result){
        res.send({'message':'删除成功'});
    })
}
/**
 * 点击小说的编辑按钮跳转到小说的信息页面，获取初始时的小说的信息
 * @param req
 * @param res
 * @param next
 */
bookApi.getInitBookData = function(req,res,next){
    var editeBookId = req.params.editeBookId;
    db.query('select * from book where bookId=?',[editeBookId],function(result){
        res.send(result);
    })
}
/**
 * 修改数据库中那个小说的信息
 * @param req
 * @param res
 * @param next
 */
bookApi.sendEditeBookData = function(req,res,next){
    if(req.body.bookName){
        db.query('update book set bookName=? where bookId=?',[req.body.bookName,req.body.bookId],function(){
            res.send({message:"修改成功"});
        });
    }
    if(req.body.style){
        db.query('update book set style=? where bookId=?',[req.body.style,req.body.bookId],function(){
            res.send({message:"修改成功"});
        });
    }
    if(req.body.introduct){
        db.query('update book set introduct=? where bookId=?',[req.body.introduct,req.body.bookId],function(){
            res.send({message:"修改成功"});
        });
    }
    if(req.body.status){
        db.query('update book set status=? where bookId=?',[req.body.status,req.body.bookId],function(){
            res.send({message:"修改成功"});
        });
    }
}
/**
 * 搜索小说
 * @param req
 * @param res
 * @param next
 */
bookApi.searchBook = function(req,res,next){
    db.query('select * from book where bookName=?',[req.body.bookName],function (result) {
        res.send(result);
    });
}
/**
 * 验证管理员帐号是否存在
 * @param req
 * @param res
 * @param next
 */
bookApi.checkAccount = function(req,res,next){
    db.query('select * from admin where adminname=?',[req.body.account],function(result){
        if(result.length == 0){
            res.send({message:"账号合格"})
        }else{
            res.send({message:'帐号已存在'})
        }
    })
}
/**
 * 获取所有的管理员
 * @param req
 * @param res
 * @param next
 */
bookApi.getAllManager = function (req,res,next) {
    db.query('select * from admin',[],function (result) {
        res.send(result);
    })
}
/**
 * 添加管理员
 * @param req
 * @param res
 * @param next
 */
bookApi.sendAdminForm = function(req,res,next){
    db.query('insert into admin (adminname,adminpassword,power) values(?,?,?)',[req.body.adminname,req.body.adminpassword,req.body.power],function(result){
        res.send({message:"添加成功"});
    })
}
bookApi.deleteAdmin = function (req,res,next) {
    db.query('delete from admin where adminname=?',[req.body.adminname],function (result) {
        res.send({message:"删除成功"});
    })
}
/**
 * 获取所有用户信息
 * @param req
 * @param res
 * @param next
 */
bookApi.getUsersInfo = function(req,res,next){
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select * from user',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select * from user limit 13 offset '+offset,[],function(result){
            res.send(result);
        })
    }
}
/**
 * 从审核评论表中获取所有的评论
 * @param req
 * @param res
 * @param next
 */
bookApi.getComment = function (req,res,next) {
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = ""',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = "" limit 13 offset '+offset,[],function(result){
            res.send(result);
        })
    }
}
//获取通过审核的所有评论
bookApi.getPassComment = function (req,res,next) {
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = "pass"',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = "pass" limit 13 offset '+offset,[],function(result){
            res.send(result);
        })
    }
}
//获取不通过审核的所有评论
bookApi.getUnpassComment =function (req,res,next) {
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = "unpass"',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select auditcomment.auditId,user.username,auditcomment.comment,book.bookName,auditcomment.commentTime from (auditcomment left join user on user.userId = auditcomment.uId) left join book on auditcomment.bId = book.bookId where result = "unpass" limit 13 offset '+offset,[],function(result){
            res.send(result);
        })
    }
}
/**
 * 处理登录
 * @param req
 * @param res
 * @param next
 */
bookApi.login = function (req,res,next) {
    var adminName = req.body.adminname;
    var adminPassword = req.body.adminpassword;
    db.query('select * from admin where adminname=?',[adminName],function(result){
        if(result.length == 0){
            return res.send({message:'帐号不正确'});
        }else{
            if(adminPassword !== result[0].adminpassword){
                return res.send({message:'密码不正确'});
            }else{
                db.query('update admin set status="online" where adminname=?',[adminName],function () {
                    return res.send({message:'登录成功',adminId:result[0].adminid,adminPower:result[0].power});
                })
            }
        }
    });
}
/**
 * 将通过审核的评论添加到评论表里
 * @param req
 * @param res
 * @param next
 */
bookApi.sendToComment = function(req,res,next){
    var auditId = req.body.auditId;
    // db.query('select * from auditComment where auditId=?',[auditId],function(result){
    //     let uId = result[0].uId;
    //     let bId = result[0].bId;
    //     let comment = result[0].comment;
    //     let commentTime = result[0].commentTime;
        // db.query('insert into comment (uId,bId,comment,commentTime) values (?,?,?,?)',[uId,bId,comment,commentTime],function (result) {
        db.query('update auditComment set result = "pass" where auditId=?',[auditId],function (result) {
            res.send({message:"通过审核"});
            // db.query('delete from auditComment where auditId=?',[auditId],function(resule){
            //
            // });
        });
    // })
}
/**
 * //将不通过审核的评论添加到为通过审核评论表里,并通过uid找到用户增加违规次数
 * @param req
 * @param res
 * @param next
 */
bookApi.sendToUnpassComment = function(req,res,next){
    var auditId = req.body.auditId;
    db.query('select * from auditComment where auditId=?',[auditId],function(result){
    //     console.log(result);
        let uId = result[0].uId;
    //     let bId = result[0].bId;
    //     let comment = result[0].comment;
    //     let commentTime = result[0].commentTime;
    //     db.query('insert into unpassComment (uId,bId,comment,commentTime) values (?,?,?,?)',[uId,bId,comment,commentTime],function (result) {
            res.send('');
            db.query('update auditComment set result = "unpass" where auditId=?',[auditId],function(resule){

            });
        // });
        //给位通过审核的用户添加违规次数
        db.query('select * from user where userId=?',[uId],function(result){
            db.query('update user set Violations=? where userId=?',[result[0].Violations+1,uId],function () {
                
            });
        });
    });
}
/**
 * 查找用户
 * @param req
 * @param res
 * @param next
 */
bookApi.searchUser = function (req,res,next) {
    db.query('select * from user where userName=?',[req.body.userName],function (result) {
        res.send(result);
    })
}
/**
 * 删除用户
 * @param req
 * @param res
 * @param next
 */
bookApi.deleteUser = function (req,res,next) {
    db.query('delete from user where userId =?',[req.body.userId],function (result) {
        res.send({message:"删除成功"});
    })
}
//
/**
 * 查看某用户的违规详情
 * @param req
 * @param res
 * @param next
 */
bookApi.checkMore = function (req,res,next) {
    db.query('select user.username,unpasscomment.comment,book.bookName from (user left join unpasscomment on user.userId = unpasscomment.uId) left join book on unpasscomment.bId = book.bookId where userId=?',[req.params.userId],function(result){
        res.send(result)
    })
}
//
/**
 * 获取所有的留言信息
 * @param req
 * @param res
 * @param next
 */
bookApi.getAllMessage  =function (req,res,next) {
    let offset = (req.params.offset-1)*13;
    if(req.params.offset == 1){
        db.query('select user.username,message.messageId,message.message,message.uInfo from (message left join user on message.uid = user.userId)',[],function (result) {
            res.send(result)
        })
    }
    else{
        db.query('select user.username,message.messageId,message.message,message.uInfo from (message left join user on message.uid = user.userId) limit 13 offset '+offset,[],function (result) {
            console.log(result);
            res.send(result);
        });
    }
}
/**
 * 已查看后删除留言
 * @param req
 * @param res
 * @param next
 */
bookApi.deleteMessage = function (req,res,next) {
    db.query('delete from message where messageId=?',[req.body.messageId],function () {
        res.send();
    })
}

/**
 * //获取所有的公告内容
 * @param req
 * @param res
 * @param next
 */
bookApi.getAllAnnouncement = function (req,res,next) {
    db.query('select * from announcement',[],function (result) {
        res.send(result);
    });
}
/**
 * //删除公告
 * @param req
 * @param res
 * @param next
 */
bookApi.deleteAnnouncement = function (req,res,next) {
    db.query('delete from announcement where announcementId =?',[req.body.announcementId],function (result) {
        res.send({message:'删除成功'});
    })
}

/**
 * //添加公告
 * @param req
 * @param res
 * @param next
 */
bookApi.addAnnouncement = function (req,res,next) {
    db.query('insert into announcement (announcement) values (?)',[req.body.announcement],function (result) {
        res.send({message:"添加成功"});
    })
}
/**
 * 添加小说
 * @param req
 * @param res
 * @param next
 */
bookApi.addBook = function (req,res,next) {
    db.query('insert into book (bookName,style,status,introduct,author,chapter) values(?,?,?,?,?,?)',[req.body.bookName,req.body.style,req.body.status,req.body.introduct,req.body.author,"no"],function (result) {
        res.send({message:'添加成功'});
    });
}


//前端接口
//获取首页轮播图信息
bookApi.frontGetIndexLunbo = function (req,res,next) {
    db.query('select * from indexLunbo',[],function (result) {
        res.send(result);
    });
}
//新作榜
bookApi.frontNewProduct = function (req,res,next) {
    db.query('select * from book where status="连载" and imgUrl <> "null" order by focusCount desc',[],function (result) {
        res.send(result);
    })
}
//完结榜
bookApi.frontEndProduct = function (req,res,next) {
    db.query('select * from book where status="完结" and imgUrl <> "null" order by focusCount desc',[],function (result) {
        res.send(result);
    })
}
//收藏榜
bookApi.frontCollectionProduct = function (req,res,next) {
    db.query('select * from book where imgUrl <> "null" order by focusCount desc',[],function (result) {
        res.send(result);
    })
}
//从收藏获取4个主编推荐信息
bookApi.frontGetRecommend = function (req,res,enxt) {
    db.query('select * from book where imgUrl <> "null" order by clickCount desc limit 4',[],function (result) {
        res.send(result);
    })
};
//从连载获取4个新作榜信息
bookApi.frontGetNewProduct = function (req,res,next) {
    db.query('select * from book where status="连载" and imgUrl <> "null" order by clickCount desc limit 4',[],function (result) {
        res.send(result);
    })
}
//新作推荐查看更多
bookApi.frontGetAllNewProduct = function (req,res,next) {
    db.query('select * from book where status="连载" and imgUrl <> "null" order by clickCount desc',[],function (result) {
        res.send(result);
    })
}
//从完结获取4个完结帮信息
bookApi.frontGetEndProduct = function (req,res,next) {
    db.query('select * from book where status="完结" and imgUrl <> "null" order by clickCount desc limit 4',[],function (result) {
        res.send(result);
    })
}
//完结推荐查看更多
bookApi.frontGetAllEndProduct = function (req,res,next) {
    db.query('select * from book where status="完结" and imgUrl <> "null" order by clickCount desc',[],function (result) {
        res.send(result);
    })
}
//从收藏获取4个收藏帮信息
bookApi.frontGetCollectionProduct = function (req,res,next) {
    db.query('select * from book where imgUrl <> "null" order by clickCount desc limit 4',[],function (result) {
        res.send(result);
    })
}
//收藏推荐查看更多
bookApi.frontCollection = function (req,res,next) {
    db.query('select * from book where imgUrl <> "null" order by clickCount desc',[],function (result) {
        res.send(result);
    })
}
//获取书架里的书的信息
bookApi.frontGetBookcase = function (req,res,next) {
    db.query('select bookcase.bId,book.bookName,book.imgUrl from (bookcase left join book on bookcase.bId = book.bookId) where uId=?',[req.query.userId],function (result) {
        res.send(result);
    });
}
//删除书架小说
bookApi.deleteBookcase = function (req,res,next) {
    db.query('delete from bookcase where bId=?',[req.body.bId],function (result) {
        res.send({code:1,message:"删除成功"});
    })
}
//根据搜索的小说名，作者名获取搜索的小说
bookApi.frontSearchBook = function (req,res,next) {
    console.log(req.query.value);
    db.query('select * from book where (bookname like ? or author like ?) and imgUrl <> "null"',["%"+req.query.value+"%","%"+req.query.value+"%"],function (result) {
        res.send(result);
    })
}
//获取对应分类的小说
bookApi.frontGetClassify = function (req,res,next) {
    console.log(req.query.type+"===================");
    db.query('select * from book where (style=? or style1=?) and imgUrl <> "null"',[req.query.type,req.query.type],function (result) {
        res.send(result);
    })
}
//获取留言
bookApi.frontGetMessage = function (req,res,next) {
    db.query('insert into message (uid,message,uInfo) values (?,?,?)',[req.body.uId,req.body.message,req.body.uInfo],function () {
        res.send({code:1,message:"管理员已收到你的留言，会尽快审核喔"});
    });
}
//小说页面
bookApi.frontGetBookDetail = function (req,res,next) {
    db.query('select * from book where bookId=?',[req.query.bookId],function (result) {
        //将字符串转化成数组
        console.log(result[0].chapter);
        result[0].chapters = result[0].chapter.split('|');
        console.log(result[0].chapters);
        for (var i = 0; i < result[0].chapters.length; i++) {
            result[0].chapters[i] = JSON.parse(result[0].chapters[i]);
        }
        res.send(result);
    })
}
//获取每一章
bookApi.frontGetNovel = function (req,res,next) {
    var data = '';
    // 创建可读流
    var readerStream = fs.createReadStream('/book/public/text/'+req.query.chapter+'.txt');

    // 设置编码为 utf8。
    readerStream.setEncoding('UTF8');

    // 处理流事件 --> data, end, and error
    readerStream.on('data', function(chunk) {
        data += chunk;
    });

    readerStream.on('end',function(){
        res.send({data:data});
    });

    readerStream.on('error', function(err){
        console.log(err.stack);
    });
}
//点击加入书架
bookApi.frontAddToBookcase = function (req,res,next) {
    db.query('select * from bookcase where bId=?',[req.body.bId],function (result) {
        if(result.length==0){
            db.query('insert into bookcase (uId,bId) values (?,?)',[req.body.uId,req.body.bId],function (rsult) {
                res.send({code:1,message:"已添加到书架"});
            })
        }else{
            res.send({code:0,message:'此书已添加到书架'});
        }
    })
}
//获取10条评论
bookApi.frontGetComment = function (req,res,next) {
    db.query('select auditcomment.auditId,auditcomment.comment,auditcomment.commentTime,auditcomment.good,user.userName from (auditcomment left join user on auditcomment.uId = user.userId) where bId=? and result="pass" limit 10',[req.query.bookId],function (result) {
        res.send(result);
    })
}
//获取所有的评论
bookApi.frontGetAllComment = function (req,res,next) {
    db.query('select auditcomment.auditId,auditcomment.comment,auditcomment.commentTime,auditcomment.good,user.userName from (auditcomment left join user on auditcomment.uId = user.userId) where uId=? and result="pass"',[req.query.bookId],function (result) {
        res.send(result);
    })
}
//发表评论
bookApi.frontSendComment = function (req,res,next) {
    db.query('insert into auditComment (uId,bId,comment,commentTime) values(?,?,?,now())',[req.body.uId,req.body.bId,req.body.comment],function (result) {
        res.send({code:1,message:"评论已提交，正在审核中"});
    })
}
//评论点赞功能
bookApi.addGood = function (req,res,next) {
    db.query('update auditcomment set good=good+1 where auditId=?',[req.query.auditId],function () {
        res.send({code:1});
    })
}

//注册
bookApi.frontRegister = function (req,res,next) {
    db.query('select * from user where username=?',[req.body.username],function (result) {
        if(result.length != 0){
            res.send({code:0,message:'用户名已存在'});
        }
        else if(req.body.password){
            db.query('insert into user (username,password) values(?,?)',[req.body.username,req.body.password],function (result) {
                res.send({code:1,message:"注册成功"});
            });
        }
    })
}
//登录
bookApi.frontLogin = function (req,res,next) {
    console.log(req.body.username);
    db.query('select * from user where username=?',[req.body.username],function (result) {
        if(result.length == 0){
           return res.send({code:0,message:"用户名不存在"});
        }
        if(result[0].password != req.body.password){
            res.send({code:0,message:"密码不正确"});
        }else{
            res.send({code:1,message:'登录成功',userId:result[0].userId});
        }
    })

}
//个人中心

module.exports = bookApi;